package org.jeecg.modules.basic.warehouse.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.BeanUtil;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseArea;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseAreaLocation;
import org.jeecg.modules.basic.warehouse.entity.vo.BasicWarehouseVO;
import org.jeecg.modules.basic.warehouse.entity.vo.WmsBasicWarehousePageVO;
import org.jeecg.modules.basic.warehouse.entity.vo.WmsBasicWarehouseQueryVO;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.mapper.WmsRepertoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 仓库
 * @Author: jeecg-boot
 * @Date: 2023-08-09
 * @Version: V1.0
 */
@Service
public class WmsBasicWarehouseServiceImpl extends ServiceImpl<WmsBasicWarehouseMapper, WmsBasicWarehouse> implements IWmsBasicWarehouseService {

    @Autowired
    private IWmsBasicWarehouseAreaService wmsBasicWarehouseAreaService;
    @Resource
    private WmsRepertoryMapper wmsRepertoryMapper;
    @Autowired
    @Lazy
    private IWmsBasicWarehouseAreaLocationService wmsBasicWarehouseAreaLocationService;

    @Override
    public List<BasicWarehouseVO> listTree() {
        List<WmsBasicWarehouse> warehouses = this.list(new LambdaQueryWrapper<WmsBasicWarehouse>()
                .eq(WmsBasicWarehouse::getStatus, BigDecimal.ROUND_DOWN)
                .eq(WmsBasicWarehouse::getDelFlag, BigDecimal.ROUND_UP));
        List<BasicWarehouseVO> basicWarehouseVOS = BeanUtil.copyToList(warehouses, BasicWarehouseVO.class);
        List<WmsBasicWarehouseArea> areas = wmsBasicWarehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                .eq(WmsBasicWarehouseArea::getStatus, BigDecimal.ROUND_DOWN)
                .eq(WmsBasicWarehouseArea::getDelFlag, BigDecimal.ROUND_UP));

        List<WmsBasicWarehouseAreaLocation> areaLocations = wmsBasicWarehouseAreaLocationService.list(new LambdaQueryWrapper<WmsBasicWarehouseAreaLocation>()
                .eq(WmsBasicWarehouseAreaLocation::getStatus, BigDecimal.ROUND_DOWN)
                .eq(WmsBasicWarehouseAreaLocation::getDelFlag, BigDecimal.ROUND_UP));

        basicWarehouseVOS.forEach(b -> {
            ArrayList<BasicWarehouseVO> children = new ArrayList<>();
            areas.forEach(a -> {
                if (b.getId().equals(a.getWmsBasicWarehouseId())) {
                    BasicWarehouseVO basicWarehouseVO = cn.hutool.core.bean.BeanUtil.copyProperties(a, BasicWarehouseVO.class);
                    basicWarehouseVO.setExtraId(a.getWmsBasicWarehouseId());
                    children.add(basicWarehouseVO);
                    b.setChildren(children);
                }
            });

//            if (CollectionUtil.isNotEmpty(children)) {
//                ArrayList<BasicWarehouseVO> children1 = new ArrayList<>();
//                children.forEach(t -> {
//                    areaLocations.forEach(location -> {
//                        if (t.getId().equals(location.getWmsBasicWarehouseAreaId()) && t.getExtraId().equals(location.getWmsBasicWarehouseId())) {
//                            BasicWarehouseVO basicWarehouseVO = cn.hutool.core.bean.BeanUtil.copyProperties(location, BasicWarehouseVO.class);
//                            children1.add(basicWarehouseVO);
//                            t.setChildren(children1);
//                        }
//                    });
//                });
//            }

        });
        return basicWarehouseVOS;
    }

    @Override
    public void updateByCheck(WmsBasicWarehouse wmsBasicWarehouse) {
        if ("0".equals(wmsBasicWarehouse.getStatus())) {
            List<WmsRepertory> list = wmsRepertoryMapper.selectList(new LambdaQueryWrapper<WmsRepertory>().eq(WmsRepertory::getWmsBasicWarehouseId, wmsBasicWarehouse.getId()));
            if (ObjectUtil.isNotEmpty(list)) {
                throw new JeecgBootException("该仓库有库存物料，不可禁用！");
            }
        }
        if ("N".equals(wmsBasicWarehouse.getIsUseArea())) {
            List<WmsRepertory> list = wmsRepertoryMapper.selectList(new LambdaQueryWrapper<WmsRepertory>()
                    .eq(WmsRepertory::getWmsBasicWarehouseId, wmsBasicWarehouse.getId()));
            if (list.stream().anyMatch(a -> StringUtils.isNotBlank(a.getWmsBasicWarehouseAreaId()) || StringUtils.isNotBlank(a.getWmsBasicWarehouseAreaLocationId()))) {
                throw new JeecgBootException("该仓库下库区库位有库存物料，不可关闭库区管理！");
            }
        }
        this.updateById(wmsBasicWarehouse);
        //启用库区管理,最大容量和预警容量是仓库下面库区对应属性的总和
        if ("Y".equals(wmsBasicWarehouse.getIsUseArea())) {
            List<WmsBasicWarehouseArea> list = wmsBasicWarehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                    .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, wmsBasicWarehouse.getId())
            );
            this.update(new LambdaUpdateWrapper<WmsBasicWarehouse>()
                    .eq(WmsBasicWarehouse::getId, wmsBasicWarehouse.getId())
                    .set(WmsBasicWarehouse::getMaxCapacity, list.stream().filter(s -> ObjectUtil.isNotNull(s.getMaxCapacity())).map(WmsBasicWarehouseArea::getMaxCapacity).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .set(WmsBasicWarehouse::getMaxCapacityAssist, list.stream().filter(s -> ObjectUtil.isNotNull(s.getMaxCapacityAssist())).map(WmsBasicWarehouseArea::getMaxCapacityAssist).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .set(WmsBasicWarehouse::getMinCapacity, list.stream().filter(s -> ObjectUtil.isNotNull(s.getMinCapacity())).map(WmsBasicWarehouseArea::getMinCapacity).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .set(WmsBasicWarehouse::getMinCapacityAssist, list.stream().filter(s -> ObjectUtil.isNotNull(s.getMinCapacityAssist())).map(WmsBasicWarehouseArea::getMinCapacityAssist).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .set(WmsBasicWarehouse::getWarningCapacity, list.stream().filter(s -> ObjectUtil.isNotNull(s.getWarningCapacity())).map(WmsBasicWarehouseArea::getWarningCapacity).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .set(WmsBasicWarehouse::getWarningCapacityAssist, list.stream().filter(s -> ObjectUtil.isNotNull(s.getWarningCapacityAssist())).map(WmsBasicWarehouseArea::getWarningCapacityAssist).reduce(BigDecimal.ZERO, BigDecimal::add)));
        } else {
            this.update(new LambdaUpdateWrapper<WmsBasicWarehouse>()
                    .eq(WmsBasicWarehouse::getId, wmsBasicWarehouse.getId())
                    .set(WmsBasicWarehouse::getMaxCapacity, wmsBasicWarehouse.getMaxCapacity())
                    .set(WmsBasicWarehouse::getMaxCapacityAssist, wmsBasicWarehouse.getMaxCapacityAssist())
                    .set(WmsBasicWarehouse::getMinCapacity, wmsBasicWarehouse.getMinCapacity())
                    .set(WmsBasicWarehouse::getMinCapacityAssist, wmsBasicWarehouse.getMinCapacityAssist())
                    .set(WmsBasicWarehouse::getWarningCapacity, wmsBasicWarehouse.getWarningCapacity())
                    .set(WmsBasicWarehouse::getWarningCapacityAssist, wmsBasicWarehouse.getWarningCapacityAssist()));
        }
        // 若仓库禁用则将下面的库区库位都禁用
        if ("0".equals(wmsBasicWarehouse.getStatus())) {
            List<WmsBasicWarehouseArea> areas = wmsBasicWarehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                    .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, wmsBasicWarehouse.getId()));
            if (CollectionUtil.isNotEmpty(areas)) {
                for (WmsBasicWarehouseArea area : areas) {
                    area.setStatus("0");
                }
                wmsBasicWarehouseAreaService.updateBatchById(areas);
                List<String> areaIds = areas.stream().map(WmsBasicWarehouseArea::getId).collect(Collectors.toList());
                wmsBasicWarehouseAreaLocationService.update(new LambdaUpdateWrapper<WmsBasicWarehouseAreaLocation>()
                        .in(WmsBasicWarehouseAreaLocation::getWmsBasicWarehouseAreaId, areaIds)
                        .set(WmsBasicWarehouseAreaLocation::getStatus, "0"));
            }
        }
    }

    /**
     * 仓库-分页列表查询-2
     * @param page
     * @param queryVO
     * @return
     */
    @Override
    public IPage<WmsBasicWarehousePageVO> getPageList(IPage<WmsBasicWarehouse> page, WmsBasicWarehouseQueryVO queryVO) {
        return this.baseMapper.getPageList(page,queryVO);
    }
}
